import 'package:family_expense/features/account_user/services/join_account_group_request_service.dart';
import 'package:family_expense/features/account_user/widgets/user_shared.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class AddAccountGroupUser extends StatefulWidget {
  const AddAccountGroupUser(this.user, {super.key});

  final User user;

  @override
  State<AddAccountGroupUser> createState() => _AddAccountGroupUserState();
}

class _AddAccountGroupUserState extends State<AddAccountGroupUser> {
  final JoinAccountGroupRequestService _joinAccountGroupRequestService =
      JoinAccountGroupRequestService();

  late final User _user = widget.user;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('添加用户')),
      body: _buildBody(),
    );
  }

  /// Builds the input form.
  Widget _buildBody() {
    // DO NOT PUT [Form] in [ListView]. Uses [SingleChildScrollView] instead.
    // Textfield in gallery gets reset if scrolled out of view.
    // https://github.com/flutter/flutter/issues/11500
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const ListCaption('基本信息'),
          ListTile(
            leading: Hero(
              tag: _user.id!,
              transitionOnUserGestures: true,
              child: UserAvatorView(_user),
            ),
            title: Text(
              _user.fullName!,
              overflow: TextOverflow.ellipsis,
              style: Theme.of(context).textTheme.titleLarge,
            ),
            subtitle: _buildUsernameInfo(_user),
          ),
          _buildDivider(),
          const ListCaption('角色设置'),
          AccountGroupUserRoleSelection(_user.fullRoles!, (selectedRoles) {
            if (mounted) {
              setState(() => _user.fullRoles = selectedRoles);
            }
          }),
          _buildDivider(),
          Container(
            margin: const EdgeInsets.only(top: 40.0),
            height: 44.0,
            child: PressStatusButton(
              disabledChild: const Text(
                '正在发送',
                style: TextStyle(fontSize: 20.0),
              ),
              onPressed: _send,
              child: const Text('发送邀请', style: TextStyle(fontSize: 20.0)),
            ),
          ),
        ],
      ),
    );
  }

  /// Builds divider between list tile.
  Widget _buildDivider() {
    return const SizedBox(height: 20.0);
  }

  /// Builds to show username info.
  Widget _buildUsernameInfo(User user) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const Icon(Icons.phone_android, size: 20.0, color: Colors.grey),
        const SizedBox(width: 6.0),
        Text(
          user.username!.formatMobilePhoneNumber(),
          style: Theme.of(
            context,
          ).textTheme.titleMedium!.copyWith(fontSize: 14.0, color: Colors.grey),
        ),
      ],
    );
  }

  /// Saves the new [User] to server and pops.
  /// When pops notify previous page to reload.
  Future<void> _send() async {
    if (_user.fullRoles!.isEmpty) {
      showToast('请设置用户角色');
      return;
    }

    // Saves the new user and pops if successful.
    final success = await _joinAccountGroupRequestService.send(_user);

    if (success) {
      showToast('邀请已成功发送给 ${_user.username!.formatMobilePhoneNumber()}');

      // DO NOT use BuildContext across asynchronous gaps.
      // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
      if (mounted) {
        // Pops current page and notifies the last page to update the list.
        NavigatorHelper.pop(context);
      }
    }
  }
}
